<template>
  <div class="tree-box">
    <!-- 清空勾选内容 -->
    <label @click="resetChecked" class="reset">清空</label>
    <!-- 目录菜单树 -->
    <el-tree :data="tree" show-checkbox default-expand-all node-key="id" ref="tree" highlight-current :default-checked-keys="treeMenus">
      <!-- 显示节点名称 -->
      <span class="custom-tree-node" slot-scope="{ node }">
        <span>{{ node.label }}</span>
      </span>
    </el-tree>
  </div>
</template>

<script>
export default {
  // 接收父节点数据
  props: {
    // 目录树
    trees: {
      type: Array
    },
    // 选中树
    setTree: {
      type: Array
    }
  },

  // 当前实例数据
  data () {
    return {
      // 树菜单
      treeMenus: [],

      // 树Dom数据
      tree: [],

      // 授权目录菜单数据
      roleMenus: []
    };
  },

  // 创建实例后执行
  created () {
    // 显示树节点
    this.showTree();
  },

  methods: {
    // 获取选中树
    getCheckedKeys () {
      return this.$refs.tree.getCheckedKeys();
    },

    // 设置选中树
    setCheckedKeys (data) {
      this.$refs.tree.setCheckedKeys(data);
    },

    // 清空
    resetChecked () {
      this.$refs.tree.setCheckedKeys([]);
    },

    // 显示树节点
    showTree () {
      let _self = this;
      let lv1 = [];
      let lv2 = [];

      // 循环获取一级菜单
      _self.trees.map(item => {
        if (item.parentId === 0) {
          lv1.push({
            id: item.id,
            label: item.menuName,
            children: []
          });
        } else {
          // 二级菜单生成
          lv2.push({
            parentId: item.parentId,
            id: item.id,
            label: item.menuName
          });
        }
      });

      // 避免数据重复
      for (let i = 0; i < lv1.length; i++) {
        for (let j = 0; j < lv2.length; j++) {
          if (lv2[j].parentId === lv1[i].id) {
            lv1[i].children.push(lv2[j]);
          }
        }
      }

      // 树节点数据赋值
      this.tree = lv1;
    }
  }
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
